#pragma once
#include<iostream>
template<class K, class V>
struct BSTreeNode
{
	BSTreeNode(const K& key = K(), const V& val = V())
		:_key(key)
		,_value(val)
	{}
	K _key;
	V _value;
	BSTreeNode* _left = nullptr;
	BSTreeNode* _right = nullptr;

};

template<class K, class V>
class BSTree
{
	typedef BSTreeNode<K, V> Node;
public:
	bool Insert(const K& key, const V& value = V())
	{
		if (!_root)
		{
			_root = new Node(key, value);
			return true;
		}
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (key < cur->_key)
			{
				parent = cur;
				cur = cur->_left;
				if (cur == nullptr)
				{
					cur = new Node(key, value);
					parent->_left = cur;
					return true;
				}
			}
			else if (key > cur->_key)
			{
				parent = cur;
				cur = cur->_right;
				if (cur == nullptr)
				{
					cur = new Node(key, value);
					parent->_right = cur;
					return true;
				}
			}
		}
		return false;
	}
	Node* Find(const K& key)
	{
		if (!_root)
		{
			return nullptr;
		}
		Node* cur = _root;
		while (cur)
		{
			if (key < cur->_key)
			{
				cur = cur->_left;
			}
			else if (key > cur->_key)
			{
				cur = cur->_right;
			}
			else
			{
				return cur;
			}
		}
		return nullptr;
	}
	bool Erase(const K& key)
	{
		Node* parent = nullptr;
		Node* cur = _root;
		while (cur)
		{
			if (cur->_key < key)
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (cur->_key > key)
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				if (cur->_left == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_right;
						return true;
					}
					else
					{
						if (cur == parent->_right)
						{
							parent->_right = cur->_right;
						}
						else if(cur == parent->_left)
						{
							parent->_left = cur->_right;
						}
						delete cur;
						return true;
					}
				}
				else if(cur->_right == nullptr)
				{
					if (cur == _root)
					{
						_root = cur->_left;
						return true;
					}
					else
					{
						if (cur == parent->_left)
						{
							parent->_left = cur->_left;
						}
						else if (cur == parent->_right)
						{
							parent->_right = cur->_left;
						}
						delete cur;
						return true;
					}
				}
				else
				{
					Node* rightMinParent = cur;
					Node* rightMin = cur->_right;
					while (rightMin->_left)
					{
						rightMinParent = rightMin;
						rightMin = rightMin->_left;
					}
					cur->_key = rightMin->_key;
					cur->_value = rightMin->_value;
					rightMinParent->_left = rightMin->_right;
					delete rightMin;
					return true;
				}
			}
		}
		return false;
	}
	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_InOrder(root->_left);
		std::cout << root->_key << ":" << root->_value << std::endl;
		_InOrder(root->_right);
	}
	void InOrder()
	{
		_InOrder(_root);
	}
private:
	Node* _root = nullptr;
};